import React, { useState, useEffect, memo } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  ColorPicker,
  Space,
  Radio,
  Card,
  Row,
  Col,
  Empty,
  Tag,
  Button,
  Spin,
} from 'antd';
import type { Color } from 'antd/es/color-picker';
import {
  FolderOutlined,
  BulbOutlined,
  RocketOutlined,
  BookOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  CloseCircleOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import type { CreateProjectDto, ProjectTemplate } from '@/types/project';
import { useModelConfigStore } from '@/stores/model-config.store';
import { useTemplateStore } from '@/stores/template.store';
import './style.css';

const { TextArea } = Input;
const { Option } = Select;

interface CreateProjectModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: (data: CreateProjectDto) => Promise<void>;
  loading?: boolean;
}

// 预设项目模板
const PROJECT_TEMPLATES: ProjectTemplate[] = [
  {
    id: 'blank',
    name: '空白项目',
    description: '从零开始创建',
    icon: 'FolderOutlined',
    color: '#1890ff',
    settings: {
      language: 'zh',
      tone: 'professional',
    },
  },
  {
    id: 'news',
    name: '新闻报道',
    description: '快讯、深度、专题',
    icon: 'FileTextOutlined',
    color: '#fa8c16',
    settings: {
      language: 'zh',
      tone: 'professional',
    },
  },
  {
    id: 'creative',
    name: '创意写作',
    description: '小说、散文、诗歌',
    icon: 'BulbOutlined',
    color: '#722ed1',
    settings: {
      language: 'zh',
      tone: 'creative',
    },
  },
  {
    id: 'marketing',
    name: '营销文案',
    description: '广告、推广、产品',
    icon: 'RocketOutlined',
    color: '#eb2f96',
    settings: {
      language: 'zh',
      tone: 'professional',
    },
  },
  {
    id: 'technical',
    name: '技术文档',
    description: '教程、说明、规范',
    icon: 'BookOutlined',
    color: '#13c2c2',
    settings: {
      language: 'zh',
      tone: 'professional',
    },
  },
  {
    id: 'article',
    name: '文章博客',
    description: '资讯、观点、分析',
    icon: 'FileTextOutlined',
    color: '#52c41a',
    settings: {
      language: 'zh',
      tone: 'casual',
    },
  },
];

const ICON_MAP: Record<string, React.ReactNode> = {
  FolderOutlined: <FolderOutlined />,
  BulbOutlined: <BulbOutlined />,
  RocketOutlined: <RocketOutlined />,
  BookOutlined: <BookOutlined />,
  FileTextOutlined: <FileTextOutlined />,
};

export const CreateProjectModal = memo<CreateProjectModalProps>(
  ({ open, onCancel, onOk, loading = false }) => {
    const [form] = Form.useForm();
    const [selectedTemplate, setSelectedTemplate] = useState<string>('blank');
    const [projectColor, setProjectColor] = useState<string>('#1890ff');

    // 获取模型配置
    const { configs, loading: modelsLoading, loadConfigs } = useModelConfigStore();

    // 获取模板数据
    const { templates, loading: templatesLoading, loadTemplates } = useTemplateStore();

    useEffect(() => {
      if (open) {
        loadConfigs();
        loadTemplates();
      }
    }, [open, loadConfigs, loadTemplates]);

    // 获取可用的激活模型
    const availableModels = configs.filter(c => c.isActive === true);
    const healthyModels = availableModels.filter(c => c.status === 'healthy');
    const unknownModels = availableModels.filter(c => c.status === 'unknown');
    const unhealthyModels = availableModels.filter(c => c.status === 'unhealthy');

    // 将数据库模板转换为项目模板格式
    const databaseTemplates: ProjectTemplate[] = templates.map(t => ({
      id: t.id,
      name: t.name,
      description: t.description || '',
      icon: getCategoryIcon(t.category),
      color: getCategoryColor(t.category),
      settings: {
        language: t.language || 'zh',
        tone: 'professional',
      },
    }));

    // 合并预设模板和数据库模板
    const allTemplates = [...PROJECT_TEMPLATES, ...databaseTemplates];

    // 获取分类图标
    function getCategoryIcon(category: string): string {
      const iconMap: Record<string, string> = {
        news: 'FileTextOutlined',
        product: 'RocketOutlined',
        tech: 'BookOutlined',
        blog: 'FileTextOutlined',
        creative: 'BulbOutlined',
        marketing: 'RocketOutlined',
      };
      return iconMap[category] || 'FileTextOutlined';
    }

    // 获取分类颜色
    function getCategoryColor(category: string): string {
      const colorMap: Record<string, string> = {
        news: '#fa8c16',
        product: '#eb2f96',
        tech: '#13c2c2',
        blog: '#52c41a',
        creative: '#722ed1',
        marketing: '#f5222d',
      };
      return colorMap[category] || '#1890ff';
    }

    const handleTemplateSelect = (templateId: string) => {
      setSelectedTemplate(templateId);
      const template = allTemplates.find((t) => t.id === templateId);
      if (template) {
        setProjectColor(template.color);
        form.setFieldsValue({
          settings: template.settings,
        });
      }
    };

    const handleColorChange = (color: Color) => {
      setProjectColor(color.toHexString());
    };

    const handleOk = async () => {
      try {
        const values = await form.validateFields();
        await onOk({
          ...values,
          color: projectColor,
        });
        form.resetFields();
        setSelectedTemplate('blank');
        setProjectColor('#1890ff');
      } catch (error) {
        console.error('Validation failed:', error);
      }
    };

    const handleCancel = () => {
      form.resetFields();
      setSelectedTemplate('blank');
      setProjectColor('#1890ff');
      onCancel();
    };

    return (
      <Modal
        title="新建项目"
        open={open}
        onCancel={handleCancel}
        onOk={handleOk}
        confirmLoading={loading}
        width={720}
        destroyOnClose
        okText="创建"
        cancelText="取消"
        className="create-project-modal"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            settings: {
              language: 'zh',
              tone: 'professional',
              autoSave: true,
            },
          }}
        >
          {/* 选择模板 */}
          <Form.Item label="选择模板">
            {templatesLoading ? (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <Spin />
                <div style={{ marginTop: 12, color: '#8c8c8c' }}>加载模板中...</div>
              </div>
            ) : (
              <Row gutter={[12, 12]}>
                {allTemplates.map((template) => (
                  <Col xs={12} sm={8} key={template.id}>
                    <Card
                      hoverable
                      className={`template-card ${
                        selectedTemplate === template.id ? 'selected' : ''
                      }`}
                      onClick={() => handleTemplateSelect(template.id)}
                      style={{
                        borderColor:
                          selectedTemplate === template.id ? template.color : undefined,
                      }}
                    >
                      <div className="template-content">
                        <div
                          className="template-icon"
                          style={{ color: template.color }}
                        >
                          {ICON_MAP[template.icon] || <FolderOutlined />}
                        </div>
                        <div className="template-name">{template.name}</div>
                        <div className="template-desc">{template.description}</div>
                      </div>
                    </Card>
                  </Col>
                ))}
              </Row>
            )}
          </Form.Item>

          {/* 项目名称 */}
          <Form.Item
            label="项目名称"
            name="name"
            rules={[
              { required: true, message: '请输入项目名称' },
              { max: 100, message: '项目名称不能超过100个字符' },
            ]}
          >
            <Input
              placeholder="输入项目名称"
              size="large"
              prefix={<FolderOutlined />}
            />
          </Form.Item>

          {/* 项目描述 */}
          <Form.Item
            label="项目描述"
            name="description"
            rules={[{ max: 500, message: '描述不能超过500个字符' }]}
          >
            <TextArea
              placeholder="简要描述项目用途（可选）"
              rows={3}
              showCount
              maxLength={500}
            />
          </Form.Item>

          {/* 项目颜色 */}
          <Form.Item label="项目颜色">
            <Space>
              <ColorPicker
                value={projectColor}
                onChange={handleColorChange}
                showText
                presets={[
                  {
                    label: '推荐',
                    colors: [
                      '#1890ff',
                      '#722ed1',
                      '#eb2f96',
                      '#13c2c2',
                      '#52c41a',
                      '#fa8c16',
                      '#f5222d',
                    ],
                  },
                ]}
              />
              <span style={{ color: '#8c8c8c', fontSize: '13px' }}>
                用于区分不同项目
              </span>
            </Space>
          </Form.Item>

          {/* 高级设置 */}
          <Form.Item label="语言">
            <Form.Item name={['settings', 'language']} noStyle>
              <Radio.Group>
                <Radio value="zh">中文</Radio>
                <Radio value="en">English</Radio>
              </Radio.Group>
            </Form.Item>
          </Form.Item>

          <Form.Item label="写作风格">
            <Form.Item name={['settings', 'tone']} noStyle>
              <Select placeholder="选择写作风格">
                <Option value="professional">专业</Option>
                <Option value="casual">轻松</Option>
                <Option value="creative">创意</Option>
              </Select>
            </Form.Item>
          </Form.Item>

          <Form.Item label="默认AI模型">
            <Form.Item name={['settings', 'aiModel']} noStyle>
              <Select
                placeholder="选择默认模型（可选）"
                allowClear
                loading={modelsLoading}
                notFoundContent={
                  modelsLoading ? (
                    <div style={{ textAlign: 'center', padding: '12px' }}>
                      <Spin size="small" />
                      <div style={{ marginTop: 8, color: '#8c8c8c' }}>加载模型中...</div>
                    </div>
                  ) : availableModels.length === 0 ? (
                    <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description={
                        <Space direction="vertical" size={8}>
                          <span>暂无可用模型</span>
                          <Link to="/model-config">
                            <Button
                              type="link"
                              size="small"
                              icon={<SettingOutlined />}
                            >
                              前往配置
                            </Button>
                          </Link>
                        </Space>
                      }
                    />
                  ) : null
                }
              >
                {healthyModels.length > 0 && (
                  <Select.OptGroup label={
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a' }} />
                      <span>健康模型</span>
                    </Space>
                  }>
                    {healthyModels.map((config) => (
                      <Option key={config.id} value={config.id}>
                        <Space>
                          <Tag color="success" style={{ margin: 0 }}>
                            {config.provider}
                          </Tag>
                          {config.displayName || config.modelName}
                        </Space>
                      </Option>
                    ))}
                  </Select.OptGroup>
                )}

                {unknownModels.length > 0 && (
                  <Select.OptGroup label={
                    <Space>
                      <ExclamationCircleOutlined style={{ color: '#faad14' }} />
                      <span>状态未知</span>
                    </Space>
                  }>
                    {unknownModels.map((config) => (
                      <Option key={config.id} value={config.id}>
                        <Space>
                          <Tag color="warning" style={{ margin: 0 }}>
                            {config.provider}
                          </Tag>
                          {config.displayName || config.modelName}
                        </Space>
                      </Option>
                    ))}
                  </Select.OptGroup>
                )}

                {unhealthyModels.length > 0 && (
                  <Select.OptGroup label={
                    <Space>
                      <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
                      <span>不可用</span>
                    </Space>
                  }>
                    {unhealthyModels.map((config) => (
                      <Option key={config.id} value={config.id} disabled>
                        <Space>
                          <Tag color="error" style={{ margin: 0 }}>
                            {config.provider}
                          </Tag>
                          {config.displayName || config.modelName}
                          <span style={{ color: '#8c8c8c', fontSize: '12px' }}>
                            (不可用)
                          </span>
                        </Space>
                      </Option>
                    ))}
                  </Select.OptGroup>
                )}
              </Select>
            </Form.Item>
          </Form.Item>
        </Form>
      </Modal>
    );
  }
);

CreateProjectModal.displayName = 'CreateProjectModal';
